package com.ljf.admin.config;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Filter配置
 */
@Configuration
public class FilterConfig {

    //Spring MVC中注册过滤器使用FilterRegistrationBean对象
    @Bean
    public FilterRegistrationBean<CorsFilter> filterRegistrationBean() {
        //1.构建基于Url方式的跨域配置对象
        UrlBasedCorsConfigurationSource configSource =
                new UrlBasedCorsConfigurationSource();
        //2.构建url请求规则配置
        CorsConfiguration config = new CorsConfiguration();
        //2.1允许所有请求头跨域
        config.addAllowedHeader("*");
        //2.2允许所有请求方式(get,post,put,...)
        config.addAllowedMethod("*");//"GET", "POST", "DELETE", "PUT"
        //2.3允许所有请求ip,port跨域
//        config.addAllowedOrigin("*");//http://ip:port   //报错：When allowCredentials is true, allowedOrigins cannot contain the special value
        config.addAllowedOriginPattern("*");//http://ip:port
        //2.4允许携带cookie进行跨域
        config.setAllowCredentials(true);
        //2.5跨域允许时间
        config.setMaxAge(3600L);
        //2.6将这个跨域配置应用到具体的url
        configSource.registerCorsConfiguration("/**", config);
        //3.注册过滤器
        FilterRegistrationBean<CorsFilter> fBean = new FilterRegistrationBean<>(new CorsFilter(configSource));
        //设置过滤器优先级
        fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return fBean;
    }


}
